package com.liqi.frame.comm.util;

import cn.hutool.core.lang.Console;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Ajax工具类
 * Created by liqi on 2017/8/9.
 */
public class AjaxUtil {

    /**
     * 是否是Ajax请求
     * @param request 请求对象
     * @return 是否是Ajax请求
     */
    public static boolean isAjax(ServletRequest request){
        return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"));
    }


    /**
     * response 输出JSON
     * @param response ServletResponse
     * @param result 输出JSON
     */
    public static void out(ServletResponse response, Object result){
        PrintWriter out = null;
        ServletOutputStream outputStream = null;
        try {
//            response.setCharacterEncoding("UTF-8");
//            out = response.getWriter();
//            out.println(JSONUtil.parse(result).toString());

            outputStream = response.getOutputStream();
            String json = new ObjectMapper().writeValueAsString(result);
            outputStream.write(json.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            Console.error(e, "输出JSON报错。");
        }finally{
//            if(null != out){
//                out.flush();
//                out.close();
//            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
